package cn.yzgy.yzgyoa.common.aspect;

import cn.yzgy.yzgyoa.common.crsp.Urmf;
import cn.yzgy.yzgyoa.common.service.impl.SysDictService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 数据字典切面
 *
 * @author Yqsen
 * @since 2021-03-18 15:36:50
 */
@Slf4j
@Aspect
@Component
public class SysDictAspect {

    @Autowired
    private SysDictService dictValueService;

    @Pointcut("(execution(public * cn.yzgy.yzgyoa.*.*.controller.*.*(..)) || execution( * cn.yzgy.yzgyoa.*.controller.*.*(..))) && @annotation(cn.yzgy.yzgyoa.common.annotation.EnableDict)")
    public void pointCut() {

    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object res = joinPoint.proceed();
        long timeStart = System.currentTimeMillis();
        log.info("开始进行字典处理.");
        if (!(res instanceof Urmf)) {
            res = dictValueService.injectDictObject(res);
        } else {
            injectUrmfDict(res);
        }
        log.info("字典处理完毕，耗时：{} ms", System.currentTimeMillis() - timeStart);
        return res;
    }

    /**
     * 注入字典值
     *
     * @param res 待注入对象
     */
    private void injectUrmfDict(Object res) {
        String data = "data";
        if (((Urmf) res).get(data) instanceof List) {
            ((Urmf) res).put(data,dictValueService.injectDictList(((Urmf) res).get(data)));
        } else if (((Urmf) res).get(data) instanceof IPage) {
            ((IPage) ((Urmf) res).get(data)).setRecords(dictValueService.injectDictList(((IPage) ((Urmf) res).get(data)).getRecords()));
        } else if (((Urmf) res).get(data) instanceof Object) {
            ((Urmf) res).put(data,dictValueService.injectDictObject(((Urmf) res).get(data)));
        }
    }


}
